#!/bin/bash

# 基础变量
website_dir="/www/wwwroot/beifen.com"
backup_dir="/www/wwwroot/beifen"
db_name="malisphere11"
db_user="malisphere11"
db_pass="x7SRaAczjYHN38Me"
db_host="localhost"
target_server="目标服务器ip"
target_user="root"
target_port="58115"
target_path="/www/wwwroot/beifen.com"
timestamp=$(date +"%Y-%m-%d_%H-%M-%S")

# 文件名
website_backup_filename="website_backup_${timestamp}.tar.gz"
db_backup_filename="db_backup_${timestamp}.sql"
website_backup_path="${backup_dir}/${website_backup_filename}"
db_backup_path="${backup_dir}/${db_backup_filename}"

# 创建备份目录
mkdir -p "$backup_dir"

echo "🔧 压缩网站源码..."
tar -czf "$website_backup_path" -C "$website_dir" .

echo "🛢 导出数据库..."
mysqldump -u"$db_user" -p"$db_pass" -h"$db_host" "$db_name" \
    --single-transaction --quick --lock-tables=false > "$db_backup_path"

echo "🔁 替换字符集..."
sed -i 's/utf8mb4_0900_ai_ci/utf8mb4_general_ci/g' "$db_backup_path"

echo "📤 上传备份文件到目标服务器..."
scp -P "$target_port" "$website_backup_path" "$db_backup_path" \
    "${target_user}@${target_server}:${target_path}"

echo "📦 导入数据库并解压网站源码..."
ssh -p "$target_port" "${target_user}@${target_server}" bash <<EOF
cd "$target_path"
mysql -u"$db_user" -p"$db_pass" "$db_name" < "$(basename "$db_backup_path")"
tar -xzf "$(basename "$website_backup_path")" -C .
rm -f "$(basename "$db_backup_path")" "$(basename "$website_backup_path")"
EOF

echo "✅ 备份和同步完成！时间：$timestamp"